<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <el-input v-model="listQuery.dataDictName" :placeholder="'请输入'+name+'名称'" class="filter-item" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="currentDataDict.dataDictName" class="filter-container" style="padding-bottom:10px">
      当前选择：
      <span class="color-primary">
        {{ currentDataDict.dataDictName+'('+currentDataDict.dataDictCode+') '+(currentDataDict.isNationalStandard==1?'标准 ':' ')+(currentDataDict.remark?currentDataDict.remark:'') }}
      </span>
      <copy-text :content="currentDataDict.dataDictCode" :show="false" style="padding-top: 11px;" />
    </div>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreateType" @refresh="handleFilter" @remove="removeRecordType">
          <template>
            <el-button icon="el-icon-refresh" plain @click="handleSyncCacheDataDict">刷新缓存</el-button>
          </template>
        </table-toolbar>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        highlight-current-row
        stripe
        height="100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="40" />
        <el-table-column align="center" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column :label="name" prop="dataDictName" min-width="150" sortable align="left">
          <template slot-scope="scope">
            <div class="flex-row">
              <div v-if="scope.row.colorValue" :style="{'background':scope.row.colorValue}" style="width: 12px;height: 12px;margin: auto 10px auto 0px;border-radius: 8px;">&nbsp;&nbsp;&nbsp;</div>
              <div> {{ scope.row.dataDictName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="name+'代码'" prop="dataDictCode" sortable width="200" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="isBuiltIn" label="标签" width="130">
          <template slot-scope="scope">
            <el-link v-if="scope.row.isBuiltIn==1" class="color-primary " :underline="false">内置</el-link>
            <el-link v-if="scope.row.isBuiltIn==0" class="color-success " :underline="false">平台</el-link>
            <el-link v-if="scope.row.isNationalStandard==1" class="color-primary " :underline="false">标准</el-link>
            <el-link v-if="scope.row.isNationalStandard==0" class="color-success " :underline="false">非标准</el-link>
          </template>
        </el-table-column>

        <el-table-column label="排序" prop="sortValue" sortable width="100" align="center" :show-overflow-tooltip="true" />

        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdateType(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingleType(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>
    <!--新增/编辑字典项侧边栏-->
    <side-box :show="sideBox.typeShow" :title="sideBox.title" @close="sideBox.typeShow = !sideBox.typeShow">
      <template slot="body">
        <el-form
          ref="typeForm"
          :rules="dataDictItemRules"
          :model="dataDictItemRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="所属字典组:">
            <el-input v-model="currentDataDict.dataDictName" :disabled="true" />
          </el-form-item>
          <el-form-item :label="name+'代码:'" prop="dataDictCode">
            <el-input v-model="dataDictItemRecord.dataDictCode" :disabled="sideBox.status==='update'" maxlength="40" placeholder="请输入" show-word-limit />
          </el-form-item>
          <el-form-item :label="name+'名称:'" prop="dataDictName">
            <el-input v-model="dataDictItemRecord.dataDictName" placeholder="请输入" maxlength="45" show-word-limit />
          </el-form-item>
          <el-form-item label="国家标准:" prop="isNationalStandard">
            <el-radio v-model="dataDictItemRecord.isNationalStandard" :label="0">否</el-radio>
            <el-radio v-model="dataDictItemRecord.isNationalStandard" :label="1">是</el-radio>
          </el-form-item>
          <el-form-item label="颜色值:" prop="colorValue">
            <el-color-picker v-model="dataDictItemRecord.colorValue" style="margin-top:5px" />
          </el-form-item>
          <el-form-item label="排序:" prop="sortValue">
            <el-input-number v-model="dataDictItemRecord.sortValue" placeholder="请输入排序" show-word-limit :max="99" style="width:100%" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button plain type="primary" @click="sideBox.status==='create'?createTypeData():updateTypeData()">保存</el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  props: {
    code: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: '字典项'
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        dataDictName: '',
        pid: '-1',
        sort: this.common.SORT_DEFAULT
      },
      currentDataDict: {},
      // 固定写法
      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        typeShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      dataDictItemRecord: {},
      dataDictItemRules: {
        isNationalStandard: [
          { required: true, message: '请选择是否国家标准', trigger: 'blur' }
        ],
        dataDictName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: this.commonValidate.checkInput, trigger: 'blur' }
        ],
        dataDictCode: [
          { required: true, message: '请输入代码', trigger: 'blur' },
          { validator: this.commonValidate.validateEngOrNum, trigger: 'blur' }
        ],
        sortValue: [
          { required: true, message: '请输入排序', trigger: 'blur' },
          { validator: this.commonValidate.validateNumber, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    code: function() {
      this.fetchDataDict()
    }
  },
  created() {
    this.fetchDataDict()
  },
  methods: {
    fetchDataDict() {
      if (this.code) {
        this.$store.dispatch('getDataDictByCode', this.code).then((res) => {
          this.currentDataDict = res
          if (res) {
            this.fetchData()
          }
        })
      }
    },
    async handleSyncCacheDataDict() {
      await this.$store.dispatch('cacheDataDict')
      this.msgSuccess('缓存成功')
    },

    // 固定写法开始
    /**
     * 表格全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    /**
     * 表格行单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 固定写法结束
    async fetchData() {
      this.listQuery = {
        ...this.listQuery,
        pid: this.currentDataDict.id
      }
      const response = await this.$store.dispatch('dataDictItemPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        dataDictName: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.$refs.multipleTable.clearSort()
      this.$refs.multipleTable.clearFilter()
      this.fetchData()
    },
    // 固定写法结束
    handleCreateType() {
      if (!this.currentDataDict.id) {
        this.msgWarning('请先选择数据字典组')
        return
      }
      this.dataDictItemRecord = {
        isNationalStandard: this.currentDataDict.isNationalStandard,
        sortValue: this.list == null ? 99 : 99 - this.list.length
      }
      this.sideBox = {
        status: 'create',
        typeShow: true,
        title: '新增' + this.name
      }
      this.$nextTick(() => {
        this.$refs['typeForm'].clearValidate()
      })
    },
    createTypeData() {
      this.$refs['typeForm'].validate(valid => {
        if (valid) {
          this.dataDictItemRecord.pid = this.listQuery.pid
          this.$store.dispatch('dataDictItemSave', this.dataDictItemRecord).then(response => {
            this.sideBox.typeShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.typeShow = true
          })
        }
      })
    },
    handleUpdateType(row) {
      this.dataDictItemRecord = Object.assign({}, row)
      this.sideBox.status = 'update'
      this.sideBox.typeShow = true
      this.sideBox.title = '编辑[' + this.dataDictItemRecord.dataDictName + ']'
      this.$nextTick(() => {
        this.$refs['typeForm'].clearValidate()
      })
    },
    updateTypeData() {
      this.$refs['typeForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.dataDictItemRecord)
          this.$store.dispatch('dataDictItemUpdate', tempData).then(response => {
            this.sideBox.typeShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.typeShow = true
          })
        }
      })
    },
    // 删除数据项
    handleRemoveSingleType(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecordType()
    },
    removeRecordType(nodeId) {
      if (nodeId !== undefined) {
        this.multipleSelectionRecords.push({ id: nodeId })
      }
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          if (v.isBuiltIn === 0) {
            ids.push(v.id)
          }
        })
        if (ids.length === 0) {
          this.msgWarning('你选择的数据都是内置数据,无权删除')
          return
        }
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('dataDictRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
